<script lang="ts" setup>
// 组件
import { ElMessage, ElMessageBox } from "element-plus";

//Store
import { useDrawerStoreHook } from "@/stores/modules/drawer"; // 抽屉
import { useCanvasStoreHook } from "@/stores/modules/canvas"; // 画布
import { actionOption, handleSave } from "./index"; // 顶部操作栏

// 接口
import {
  fetchCanvasPage,
  fetchDestroy,
  fetchCanvas,
} from "@/api/associationAnalysis";

import { emitter } from "@/utils/mitt";

import { graph } from "@/views/associationAnalysis/canvas/components/canvasG6/common/index";
import { isNeedStop } from "@/views/associationAnalysis/canvas/components/canvasG6/common/menuEvent";

const useDrawer = useDrawerStoreHook(); // 抽屉
const useCanvasStore = useCanvasStoreHook(); // 画布

const undoStack = ref(null); // 后退栈
const redoStack = ref(null); // 前进栈

onMounted(() => {
  nextTick(() => {
    // console.log(graph, "graph", graph.getUndoStack(), graph.getRedoStack());
    graph.on("stackchange", (e) => {
      // 撤销/重做栈发生变化时
      console.log(e, "estackchange");
      undoStack.value = e.undoStack.linkedList.head;
      redoStack.value = e.redoStack.linkedList.head;

      // setTimeout防止画布数据还没有更新完成就将现在画布数据存到现在切换的画布
      setTimeout(() => {
        // 操作栈发生变化时，缓存的节点应该更新，否则删除一个节点在添加一个节点会把删除的节点重新添加到画布上
        isNeedStop.value = true;
        const data = {
          // 现在图中的所有节点
          nodes: graph.getNodes().map((item) => item.getModel()),
          edges: graph.getEdges().map((item) => item.getModel()),
        };
        // console.log(graph.value.getNodes(), graph.value.getEdges(), data);
        useCanvasStore.setCanvas(JSON.parse(JSON.stringify(data)));
      }, 0);
    });
  });
});

// 右侧抽屉栏显示与隐藏控制按钮点击事件
const handleDrawerRight = () => {
  useDrawer.updateDrawer({ rightShow: !useDrawer.rightShow });
};

// 删除接口
const fetchDelete = async (id: string) => {
  try {
    await fetchDestroy(id);
    useCanvasStore.delCanvas(id);
    ElMessage({
      type: "success",
      message: "删除成功",
    });
  } catch (error) {
    ElMessage.error(error);
  }
};

// 删除按钮点击事件
const handleDelete = () => {
  // const canvas = useCanvasStore.getCanvas();
  // ElMessageBox.confirm(`确定删除《${canvas.name}》文件?`, "确认删除", {
  //   confirmButtonText: "删除",
  //   cancelButtonText: "取消",
  //   type: "warning",
  // }).then(() => {
  //   if (canvas.id) {
  //     // 有id，表示是数据库当中的画布，需要接口删除。并且本地删除。
  //     fetchDelete(canvas.id);
  //   } else {
  //     // 没有id，表示只是本地存储中的临时画布。本地删除。
  //     useCanvasStore.delCanvas(canvas.uuid);
  //     ElMessage({
  //       type: "success",
  //       message: "删除成功",
  //     });
  //   }
  // });
  emitter.emit("handleDeleteObject");
};

const importData = (event: Event): void => {
  const target = event.target as HTMLInputElement;
  if (!target || !target.files) return;

  const file: File = target.files[0];
  if (!file) return;

  const reader: FileReader = new FileReader();
  reader.onload = () => {
    try {
      const data = JSON.parse(reader.result as string);
      useCanvasStore.setCanvas({
        nodes: data.nodes,
        edges: data.edges,
      });
      ElMessage({
        type: "success",
        message: "导入成功",
      });
    } catch (error) {
      ElMessage({
        type: "success",
        message: "导入失败",
      });
    }
  };
  reader.readAsText(file);
};

const fileDialogShow = ref(false);
const fileImportDialogShow = ref(false);
emitter.on("handleFileShow", (typeShow) => {
  fetchPage();
  selectId.value = null;
  typeShow == "fileDialogShow"
    ? (fileDialogShow.value = true)
    : (fileImportDialogShow.value = true);
});

// list数据
const list = ref([]);
const fetchPage = async () => {
  let params = {};
  try {
    const { data } = await fetchCanvasPage("/kg-service/canvas/page", params);
    list.value = data.records;
    console.log(list.value);
  } catch (error) {
    // ElMessage.error(error);
  }
};
fetchPage();

// 选中的下标
const selectId = ref(null);
const isEdit = ref(false);

// 单击item选中，赋值下标
const handleSelect = (id: string) => {
  if (selectId.value === id) return;
  selectId.value = id;
  isEdit.value = false;
};

// 选中时添加新的样式
const getIsSelectClass = (id: string) => {
  if (selectId.value === id) return "isSelect";
  return "";
};

// 文件双击事件
const handelDbClick = async (id) => {
  let { data } = await fetchCanvas(id);
  let dataJson = null;
  try {
    dataJson = JSON.parse(data.data);
  } catch (d) {
    dataJson = {};
  }
  useCanvasStore.pushCanvas({
    id: data.id,
    uuid: data.id,
    name: data.name,
    data: dataJson,
  });
  fileDialogShow.value = false;
};

const handleOpen = () => {
  if (selectId.value === null) {
    ElMessage({
      message: "单击选中要打开的文件",
      type: "warning",
    });
    return;
  }
  handelDbClick(selectId.value);
};

const handleImport = async () => {
  if (selectId.value === null) {
    ElMessage({
      message: "单击选中要打开的文件",
      type: "warning",
    });
    return;
  }

  let { data } = await fetchCanvas(selectId.value);
  let dataJson = JSON.parse(data.data);

  console.log(data, dataJson, "data");
  emitter.emit("handleImport", dataJson);
  fileImportDialogShow.value = false;
};

const operate = (type) => {
  if (type == "chexiao" && !undoStack) return;
  if (type == "huifu" && !redoStack) return;
  emitter.emit("toolbarEvent", type);
};
</script>

<template>
  <div
    class="actionBar-main flex justify-between bg-white h-[48px] items-center border-b border-[#EDEFF4]"
  >
    <!--    左侧操作栏-->
    <input
      id="fileInput"
      style="display: none"
      type="file"
      @change="importData"
    />
    <ul class="flex">
      <li
        v-for="(item, index) in actionOption"
        :key="index"
        class="w-[105px] h-[40px] border-r border-[#EDEFF4] hover:bg-[#F5F7FA]"
      >
        <el-dropdown placement="bottom-start">
          <div class="w-[105px] h-[40px] flex justify-center items-center">
            <i :class="item.svg" class="iconfont"></i>
            <span class="title mx-[8px]">{{ item.label }}</span>
            <i class="iconfont icon_arrow_down"></i>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-for="(ele, key) in item.children" :key="key">
                <div class="h-[22px] flex items-center" @click="ele.handle()">
                  <i :class="ele.svg" class="iconfont"></i>
                  <span class="mx-[8px]">{{ ele.label }}</span>
                </div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </li>
    </ul>

    <!--   右侧操作按钮-->
    <div class="flex items-center justify-end">
      <span
        class="w-[32px] h-[32px] rounded-[4px] flex items-center justify-center"
        @click="operate('chexiao')"
      >
        <i
          class="iconfont icon_chexiao_fill"
          :class="undoStack ? 'text-[#2B1DFF]' : 'text-[#7F8A9B]'"
        ></i>
      </span>
      <span
        class="w-[32px] h-[32px] rounded-[4px] flex items-center justify-center"
        @click="operate('huifu')"
      >
        <i
          class="iconfont icon_chongzuo_fill"
          :class="redoStack ? 'text-[#2B1DFF]' : 'text-[#7F8A9B]'"
        ></i>
      </span>
      <el-button class="ml-[16px]" @click="handleDelete">删除</el-button>
      <el-button class="!ml-[16px]" type="primary" @click="handleSave">
        保存
      </el-button>
      <i
        :class="useDrawer.rightShow ? 'isDrawerOpen' : ''"
        class="iconfont icon_left_spread mx-[16px] spread"
        @click="handleDrawerRight"
      ></i>
    </div>

    <!--    打开文件弹窗-->
    <el-dialog v-model="fileDialogShow" title="打开文件" width="70%">
      <div>
        <div>
          <template v-if="!list.length">
            <el-empty description="暂无数据" />
          </template>
          <template v-else>
            <ul class="canvas-list">
              <li
                v-for="(item, index) in list"
                :key="index"
                :class="getIsSelectClass(item.id)"
                class="item"
                @click="handleSelect(item.id)"
                @dblclick="handelDbClick(item.id)"
              >
                <div class="left">
                  <img :src="item.thumbnail" alt="" />
                  <div class="mask">双击打开画布</div>
                </div>
                <div class="right">
                  <div class="title">
                    <i class="iconfont icon_share_fil text-[#FF9F4E] mr-2" />
                    {{ item.name }}
                  </div>

                  <div class="msg">
                    <span class="text-[#7F8A9B]">作者：</span>
                    <p class="text-[#222222]">{{ item.authorName }}</p>
                  </div>
                  <div class="msg">
                    <span class="text-[#7F8A9B]">修改时间：</span>
                    <p class="text-[#222222]">{{ item.updateTime }}</p>
                  </div>
                </div>
              </li>
            </ul>
          </template>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="fileDialogShow = false">取 消</el-button>
          <el-button type="primary" @click="handleOpen"> 打 开 </el-button>
        </span>
      </template>
    </el-dialog>

    <!--    导入文件弹窗-->
    <el-dialog v-model="fileImportDialogShow" title="打开文件" width="70%">
      <div>
        <div>
          <template v-if="!list.length">
            <el-empty description="暂无数据" />
          </template>
          <template v-else>
            <ul class="canvas-list">
              <li
                v-for="(item, index) in list"
                :key="index"
                :class="getIsSelectClass(item.id)"
                class="item"
                @click="handleSelect(item.id)"
              >
                <div class="left">
                  <img :src="item.thumbnail" alt="" />
                  <!-- <div class="mask">双击打开画布</div> -->
                </div>
                <div class="right">
                  <div class="title">
                    <i class="iconfont icon_share_fil text-[#FF9F4E] mr-2" />
                    {{ item.name }}
                  </div>

                  <div class="msg">
                    <span class="text-[#7F8A9B]">作者：</span>
                    <p class="text-[#222222]">{{ item.authorName }}</p>
                  </div>
                  <div class="msg">
                    <span class="text-[#7F8A9B]">修改时间：</span>
                    <p class="text-[#222222]">{{ item.updateTime }}</p>
                  </div>
                </div>
              </li>
            </ul>
          </template>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="fileImportDialogShow = false">取 消</el-button>
          <el-button type="primary" @click="handleImport"> 打 开 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.actionBar-main {
  .title {
    font-family: PingFangSC-Regular, "PingFang SC";
    font-size: 14px;
    font-weight: 400;
    line-height: 22px !important;
    color: #222;
  }

  .spread {
    transition: all 0.3s;
    transform: rotate(0deg);
  }

  .isDrawerOpen {
    transform: rotate(-180deg);
  }
}

.canvas-list {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
  justify-content: space-between;
  width: 100%;
  height: 500px;
  margin-top: 9px;
  overflow: hidden;
  overflow-y: auto;

  .item {
    display: flex;
    width: calc(50% - 8px);
    height: 200px;
    margin-bottom: 16px;
    background: #fff;
    border: 1px solid #dcdde2;
    border-radius: 4px;
    transition: 0.3s;

    .left {
      position: relative;
      flex: 1;
      height: 100%;
      overflow: hidden;
      background: #f7f8fa;

      img {
        width: 100%;
        height: 100%;
      }

      .mask {
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        font-family: PingFangSC-Regular, "PingFang SC";
        font-size: 14px;
        font-weight: 400;
        line-height: 22px;
        color: rgb(255 255 255 / 0%);
        background: rgb(34 34 34 / 0%);
        transition: 0.3s;
      }
    }

    .right {
      box-sizing: border-box;
      width: 264px;
      padding: 16px;

      .title {
        display: flex;
        align-items: center;
        margin-bottom: 16px;
        font-family: PingFangSC-Medium, "PingFang SC";
        font-size: 16px;
        font-weight: 500;
        line-height: 24px;
      }

      .msg {
        display: flex;
        margin-bottom: 11px;
        font-family: PingFangSC-Regular, "PingFang SC";
        font-size: 14px;
        font-weight: 400;
        line-height: 22px;
      }
    }

    &:hover {
      box-shadow: 0 5px 21px 0 rgb(13 22 50 / 10%);

      .mask {
        color: rgb(255 255 255 / 100%);
        background: rgb(34 34 34 / 20%);
      }
    }
  }

  .isSelect {
    border: 1px solid #2b1dff;
    box-shadow: 0 5px 21px 0 rgb(13 22 50 / 10%);

    .mask {
      color: rgb(255 255 255 / 100%) !important;
      background: rgb(34 34 34 / 20%) !important;
    }
  }
}
</style>
